
var fm = Ext.form;
var base_url = '<?php echo base64_decode($_GET['baseUrl']);?>';
var total_row = 20;
var menu_id = '<?php echo $_GET['menu_id'] ?>';
var proxy = new Ext.data.ScriptTagProxy({
 	api: {
        read : base_url+'admin/menu_item/grid.html?menu_id='+menu_id,
        create : base_url+'admin/menu_item/add.html',
        update: base_url+'admin/menu_item/add.html',
        destroy: base_url+'admin/menu_item/delete.html'
    }
});

var writer = new Ext.data.JsonWriter({
    encode: true
});
// use RowEditor for editing
    var editor = new Ext.ux.grid.RowEditor({
        saveText: 'Update'
    });
var store = new Ext.data.JsonStore({
	start : 'start',
	remoteSort: true,
    totalProperty: 'total',
    proxy: proxy,
    root: 'data',
    fields : [
              {name: 'id'},
{name: 'title'},
{name: 'link'},
{name: 'edit',type: 'string'}
          ],
	  listeners: {
	      save: function(s, b, d) {
	    	  store.save();
	      }
	  },
    writer: writer
});

var filters = new Ext.ux.grid.GridFilters({
    // encode and local configuration options defined previously for easier reuse
    encode: true, // json encode the filter query
    local: true,   // defaults to false (remote filtering)
    filters: [
        {type: 'string',dataIndex: 'title'},
{type: 'string',dataIndex: 'link'},

    ]
});
var createColModel = function () {

    var columns = [
    {header: 'ID',sort: 'id',sortable: false,dataIndex: 'id'},
{header: 'Title',sortable: false,sort: 'title',dataIndex: 'title',editor: new Ext.form.TextField({})},
{header: 'Link',sortable: false,sort: 'link',dataIndex: 'link',editor: new Ext.form.TextField({})},
{header: 'Edit',dataIndex: 'edit',sortable: false}
               ];

    return new Ext.grid.ColumnModel({
        columns: columns,
        defaults: {
            sortable: true
        }
    });
};

Ext.onReady(function() {
    Ext.QuickTips.init();

    var newsGrid = new Ext.grid.GridPanel({
        renderTo: 'news-grid',
        iconCls: 'icon-grid',
        frame: true,
        title: '&nbsp;',
        height: 300,
        store: store,
        plugins: [editor,filters],
        colModel: createColModel(),
        listeners: {
            render: {
                fn: function(){
                    store.load({
                        params: {
                            start: 0,
                            limit: total_row
                        }
                    });
                }
            }
        },
        tbar: [new Ext.form.ComboBox({
                     triggerAction: 'all',
                     lazyRender:false,
                     width:40,
                     mode: 'local',
                     store: new Ext.data.ArrayStore({
                         fields: [
                                  'id',
                                  'value'
                                 ],
                        data: [[10,'10'],[20,'20'],[50,'50'],[100,'100']]
                     }),
                     valueField: 'id',
                     displayField: 'value',
                     listeners:{
                          'select': function(combo,record ,index){
                        	  total_row = combo.getValue();
                        	  store.reload({params:{start:0, limit:total_row}});
                                  pagingBar.pageSize = total_row;
                        	  pagingBar.render();
                          }
                     }
                })
        ,'-',{
            text: 'Add',
            iconCls: 'silk-add',
            handler: onAdd
        }, '-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-', {
            text: 'Order',
            iconCls: 'silk-application-view-list',
            handler: thickBoxPopup
        }, '-'],        
        viewConfig: {
            forceFit: true
        }
    });

    function onAdd(btn, ev) {
       window.location.href = base_url+'admin/menu_item/edit/0/'+menu_id;
    }

    function onDelete() {
        Ext.MessageBox.show({
            title:'Delete item',
            msg: 'Do you really want to delete this item ?',
            buttons: Ext.MessageBox.YESNO,
            animEl: 'samplebutton',
            icon: Ext.MessageBox.QUESTION,
            fn:function(buttonId){
                if (buttonId == 'yes'){
                    var recs = newsGrid.getSelectionModel().getSelections() ;
                    if (!recs) {
                        return false;
                    }
                    for(var i in recs)
                    {
                       newsGrid.store.remove(recs[i]);
                       newsGrid.store.reload();
                    }
                }
            }
        });
    }
});
function formatDate(value){
    return value ? value.dateFormat('d-m-Y') : '';
}
function thickBoxPopup(){
	var Tree = Ext.tree;

    var tree = new Tree.TreePanel({
        useArrows: false,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        border: false,
        // auto create TreeLoader
        dataUrl: base_url+'admin/menu_item/get_nodes.html?menu_id='+menu_id,

        root: {
            nodeType: 'async',
            text: 'Root',
            draggable: false,
            id: '<?php echo $_GET['root_id'];?>'
        }
    });
    tree.on('nodedrop',function(dropEvent) {
    	//console.log(dd);
    	//console.log(dropEvent.data);
    	//alert(dropEvent.point+' '+dropEvent.target.id);
    	Ext.Ajax.request({
		   url: base_url+'admin/menu_item/move_nodes.html',
		   success: function(){
		   	store.load({
                        params: {
                            start: 0,
                            limit: total_row
                        }
                    });
		   },
		   method: 'POST',
		   params: { current_node : dropEvent.data.node.id, ref_node : dropEvent.target.id, point : dropEvent.point, menu_id : menu_id}
		});
    	
    	//alert('Old:'+oldParent.id+' New:'+newParent.id+' Index:'+index);
    });
    tree.getRootNode().expand();
    var win = new Ext.Window({
                title: 'Drag and drop items to order',
                resizable:false,
                preventBodyReset:true,
                bodyStyle:'background-color: #FFF',
                width:600,
                height: 300,                
                items: tree,
                layout: 'fit'
            });
    win.show();
}

